package com.heart.cn.client;

import java.net.InetSocketAddress;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.heart.cn.model.Cmder;
import com.heart.cn.model.HeartbeatEntity;
import com.heart.cn.service.deal.HeartbeatHandler;


/**
 * 心跳客户端
 * @author wangzh
 * @date 2019年8月1日 下午5:43:42
 */
public class HeartbeatClient implements Runnable {

	private static Logger log= LoggerFactory.getLogger(HeartbeatClient.class);

    private String serverIP = "172.16.34.160";
    private int serverPort = 8099;
    private String nodeID = UUID.randomUUID().toString();
    private boolean isRunning = true;

    //  最近的心跳时间
    private long lastHeartbeat;

    // 心跳间隔时间
    private long heartBeatInterval = 10 * 1000;
    
    
    /**
     * 客户端发送心跳
     */
    public void run() {
        try {
            while (isRunning) {
                HeartbeatHandler handler = RPCClient.getRemoteProxyObj(HeartbeatHandler.class, new InetSocketAddress(serverIP, serverPort));
                long startTime = System.currentTimeMillis();

                // 是否达到发送心跳的周期时间
                if (startTime - lastHeartbeat > heartBeatInterval) {
                	
                    log.info("Send Heart");
                    lastHeartbeat = startTime;

                    HeartbeatEntity entity = new HeartbeatEntity();
                    entity.setTime(startTime);
                    entity.setNodeID(nodeID);

 

                    // 向服务器发送心跳，并返回需要执行的命令
                    Cmder cmds = handler.sendHeartBeat(entity);

                    if (!processCommand(cmds))
                        continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

    private boolean processCommand(Cmder cmds) {
        return true;
    }

 

}
